const fs = require('fs');
const path = require("path");

/**
 * 递归创建文件
 * @param {*} dirName 
 * @param {*} mode 
 */
function mkdir(dirName, mode) {
    if (fs.existsSync(dirName)) {
        return true;
    }
    if (mkdir(path.dirname(dirName), mode)) {
        fs.mkdirSync(dirName, mode);
        return true;
    }
}
module.exports.mkdir = mkdir;

/**
 * 递归删除
 * @param {*} src 
 */
function rm(src) {
    if (fs.existsSync(src)) {
        if (isFile(src)) {
            fs.unlinkSync(src);
            return;
        }
        const files = fs.readdirSync(src);
        files.forEach((file) => {
            const curPath = path.join(src, file);
            if (isDirectory(curPath)) {
                rm(curPath);
            } else if (isFile(curPath)) {
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(src);
    } else {
        console.log("给定的路径不存在，请给出正确的路径");
    }
}
module.exports.rm = rm;

/**
 * 递归复制文件
 * @param {*} src 
 * @param {*} dst 
 */
function cp(src, dst) {
    const files = fs.readdirSync(src);
    files.forEach((file) => {
        const srcPath = path.join(src, file);
        const dstPath = path.join(dst, file);
        if (isFile(srcPath)) {
            // console.log('复制文件 ' + srcPath + ' 到 ' + dst);
            if (!fs.existsSync(dst)) {
                mkdir(dst);
            }
            fs.copyFileSync(srcPath, dstPath);
        } else if (isDirectory(srcPath)) {
            mkdir(dstPath);
            cp(srcPath, dstPath);
        }
    });
}
module.exports.cp = cp;


/**
 * 获取文件夹下所有文件路径
 * @param {*} src 
 */
function readDir(src) {
    return _readDir(src, []);
}
module.exports.readDir = readDir;

function _readDir(src, paths) {
    paths = paths || [];
    const files = fs.readdirSync(src);
    files.forEach((file) => {
        const filePath = path.join(src, file);
        if (isFile(filePath)) {
            paths.push(filePath);
        } else if (isDirectory(filePath)) {
            _readDir(filePath, paths);
        }
    });
    return paths;
}


/**
 * 是否是文件
 * @param {*} path 
 */
function isFile(path) {
    const stat = fs.statSync(path);
    return stat.isFile();
}

/**
 * 是否是文件夹
 * @param {*} path 
 */
function isDirectory(path) {
    const stat = fs.statSync(path);
    return stat.isDirectory();
}

function size(path) {
    const stat = fs.statSync(path);
    return stat.size;
}
module.exports.size = size;

module.exports.writeFile = fs.writeFileSync;

module.exports.readFile = fs.readFileSync;

/**
 * 文件或文件夹是否存在
 * @param {*} dirName 
 */
module.exports.exists = fs.existsSync;

/**
 * 拼接路径
 */
module.exports.join = path.join;

/**
 * 读取后缀
 */
module.exports.extname = path.extname;

module.exports.relative = path.relative;

module.exports.parse = path.parse;